using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Jabr.Logic.Exceptions.Handling
{
    /// <summary>
    /// Abstract class used for unhandled exception handling
    /// </summary>
    abstract class AbstractExceptionHandler
    {
        private Form m_MainAppForm;
        private AbstractExceptionForm m_CustomErrorForm;
        private delegate void m_ExceptionDelegate(Exception p_e);

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="p_cef">Form that will be displayed as info for the user</param>
        public AbstractExceptionHandler(AbstractExceptionForm p_cef, Form p_maf)
        {
            m_CustomErrorForm = p_cef;
            m_MainAppForm = p_maf;
        }

        protected abstract string SaveError(ExceptionInfo e);

        public void HandleException(Exception p_e)
        {
            if (SystemInformation.UserInteractive)
            {
                ExceptionInfo ei = new ExceptionInfo(p_e);
                string f = SaveError(ei);
                if (m_CustomErrorForm != null)
                {
                    m_CustomErrorForm.Info = ei;
                    m_CustomErrorForm.ExceptionFilename = f;
                    m_CustomErrorForm.ShowDialog();
                }
                Application.Exit();
                Environment.Exit(-1);
            }
        }

        public void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }
        public void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            if (ex == null)
            {
                return;
            }
            if (m_MainAppForm.InvokeRequired)
            {
                m_MainAppForm.Invoke(new m_ExceptionDelegate(HandleException), new object[] { ex });
            }
            else
            {
                HandleException(ex);
            }
        }
    }
}
